package Test_Web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class ShoppingCart
 */
public class ShoppingCart extends HttpServlet {
	private static final long serialVersionUID = 1L;
    ArrayList moviesInCart;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ShoppingCart() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		// Create new Session if there isn't one, otherwise keep current session
	    HttpSession session = request.getSession();
	    
	    // Create new cart if there isn't one, otherwise retrieve current cart
	    moviesInCart = (ArrayList)session.getAttribute("moviesInCart");
	    
	    // Clear cart or not
 		String clearCart = request.getParameter("clearCart");
 		if(clearCart != null)
 		{
 			if(clearCart.equals("True"))
 			moviesInCart = null;
 		}
 		
	    if (moviesInCart == null) {
	      moviesInCart = new ArrayList();
	      session.setAttribute("moviesInCart", moviesInCart);
	    }
	    
	    // Retrieve movie to add
	    String movieToAdd = request.getParameter("movieToAdd");

	    response.setContentType("text/html");
	    PrintWriter out = response.getWriter();
	    String title = "Movies in Cart";
	    String docType =
	      "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
	      "Transitional//EN\">\n";
	    out.println(docType +
	                "<HTML>\n" +
	                "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
	                "<BODY BGCOLOR=\"#FDF5E6\">\n" +
	                "<H1>" + title + "</H1>");
	    out.println("<br>");


	   synchronized(moviesInCart) 
	   {
		  if (movieToAdd != null) 
	      {
	    	// Given movie ID, add to cart
	    	// Check if movie is already in cart, if so increment the last digit to represent quantity
	    	boolean movieAlreadyInList = false;
	    	for(int i=0; i<moviesInCart.size(); i++) 
	    	{
	    		String currentMovie = (String)moviesInCart.get(i);
	    		
	    		if(currentMovie.substring(0, currentMovie.length()-1).equals(movieToAdd))
	    		{
	    			movieAlreadyInList = true;
	    			int currentMovieInt = Integer.parseInt(currentMovie);
	    			currentMovieInt++;
	    			movieToAdd = Integer.toString(currentMovieInt);
	    			moviesInCart.set(i, movieToAdd);
	    		}
	    	}

	    	// if movie not in list, add movie
	    	if (movieAlreadyInList == false)
	    	{
	    		movieToAdd += "1";
	    		moviesInCart.add(movieToAdd);
	    	}
	    	
	        out.println("<UL>");
		     
	        for(int i=0; i<moviesInCart.size(); i++) 
	        {
	          String tempMovieId = (String)moviesInCart.get(i);
	          String quantity = tempMovieId.substring(tempMovieId.length()-1, tempMovieId.length());
	          tempMovieId = tempMovieId.substring(0, tempMovieId.length()-1);
	          out.println("<LI>" + carryOutSQL(tempMovieId));
	          // Print out text box
	          out.println("<form>" +
	          		"<input type='text' value= '"+ quantity +"' name='" + tempMovieId + "'" +
	          				"</form></LI>");
	        }
	        
	        out.println("</UL>");
	      }
		  else if(movieToAdd == null)
		  {
			  out.println("<UL>");
			     
		        for(int i=0; i<moviesInCart.size(); i++) 
		        {
		          String tempMovieId = (String)moviesInCart.get(i);
		          String quantity = tempMovieId.substring(tempMovieId.length()-1, tempMovieId.length());
		          tempMovieId = tempMovieId.substring(0, tempMovieId.length()-1);
		          out.println("<LI>" + carryOutSQL(tempMovieId));
		          // Print out text box
		          out.println("<form>" +
		          		"<input type='text' value= '"+ quantity +"' name='" + tempMovieId + "'" +
		          				"</form></LI>");
		        }
		        
		        out.println("</UL>");
		  }
	      else
	      {
	        out.println("<I>No items</I>");
	      } 
	    }

	   /* Update/Wipe out empty movies
	   for(int i=0; i<moviesInCart.size(); i++) 
       {
         String tempMovieId = (String)moviesInCart.get(i);
         String tempMovieIdWithoutQuantity = tempMovieId.substring(0, tempMovieId.length() - 1);
         String tempQuantity = (String)request.getAttribute(tempMovieIdWithoutQuantity);
         
         if(tempQuantity != null)
         {
        	 moviesInCart.remove(tempQuantity);
         }
         
       }
		*/
	   
	   // Checkout and Main Menu Link
		out.println("");
		out.println("");
		out.println("");
		out.println("<a href = 'Checkout.jsp'>Check Out</a> | " +
				"<a href = 'ShoppingCart?clearCart=True'>Clear Cart</a> | " + 
				"<a href = 'MainPage.jsp'>Main Page</a> | " +
				"<a href = 'ShoppingCart'>Update Cart</a>");
		
		out.print("</body>");
		out.print("</html>");
		out.print("");
	   
	   out.println("</BODY></HTML>");
	}

	private String carryOutSQL(String movieId)
	{
		String movieName = "";
		try
		{
			try 
			{
				Class.forName("com.mysql.jdbc.Driver").newInstance();
			} 
			catch (Exception e) 
			{
				e.printStackTrace();
			}
		// Create Connection
		Connection connect;
		connect = DriverManager.getConnection("jdbc:mysql:///moviedb","testuser","testpass");
		Statement tempStatement = connect.createStatement();
		
		// Create and Execute Query
		String command = "select * from movies where id = " + movieId;
		ResultSet resultSet = tempStatement.executeQuery(command);
		
		resultSet.next();
		
		movieName = resultSet.getString("title");
		}
		catch (SQLException ex) {
            while (ex != null) {
                  System.out.println ("SQL Exception:  " + ex.getMessage ());
                  ex = ex.getNextException ();
              }  // end while
          }  // end catch SQLException
		return movieName;
	}

}
